<template>
	<view class="flex-column h100 w100">
		<uni-nav-bar :fixed="true" height="80rpx" left-icon='left' @clickLeft="gobacks" :statusBar="!globalIcon.isdouyin"
			title="新帖子"></uni-nav-bar>
		<view style="min-height: 50rpx">
			<u--textarea v-model="content" placeholder="这一刻的想法"></u--textarea>
		</view>
		<view style="padding: 0 10rpx; flex-wrap: wrap" class="colum-gap-10 flex">
			<view v-for="(item, index) in imgList" :key="index">
				<image :src="item.tempFilePath || item.thumbTempFilePath"
					style="height: 200rpx; width: 200rpx; object-fit: cover"></image>
			</view>
			<view class="relative center" style="
          background-color: #cccccc;
          width: 200rpx;
          height: 200rpx;
          display: flex;
        " @click="choise">
				<view class="line"></view>
				<view class="line" style="transform: rotateZ(90deg)"></view>
			</view>
		</view>
		<view class="flex-column" style="margin-top: 40rpx">
			<!-- #ifndef MP-TOUTIAO -->
			<view class="flex border" @click="goLocation">
				<u-icon name="map" size="23"></u-icon>
				<text style="flex: 1; padding-left: 20rpx">{{ location }}</text>
				<u-icon name="arrow-right" size="23"></u-icon>
			</view>
			<!-- <view class="flex border">
				<u-icon :name="globalIcon.ai" size="23"></u-icon>
				<text style="flex: 1; padding-left: 20rpx">提醒谁看</text>
				<u-icon name="arrow-right" size="23"></u-icon>
			</view> -->
			<view class="flex border">
				<u-icon :name="globalIcon.sync" size="23"></u-icon>
				<text style="flex: 1; padding-left: 20rpx">是否同步到ins</text>
				<text>{{ isSync }}</text>
				<u-icon name="arrow-right" size="23"></u-icon>
			</view>
			<!-- #endif -->
			<!-- <view class="flex border" @click="look">
				<u-icon name="account" size="23"></u-icon>
				<text style="flex: 1; padding-left: 20rpx">谁可以看</text>
				<text>{{ permission }}</text>
				<u-icon name="arrow-right" size="23"></u-icon>
			</view> -->
		</view>
		<u-button type="primary" text="发布" @click="release"></u-button>
		<u-action-sheet @select="selectClick" :actions="list" title="帖子权限" :show="show"></u-action-sheet>
		<u-action-sheet @select="selectSyncClick" :actions="syncList" title="是否同步" :show="syncShow"></u-action-sheet>
	</view>
</template>

<script>
import {
	randId
} from "@/utils/utils.js";
import Config from "@/common/config.js"
import {
	getMedias,
	getUserEdge,
	addUserEdge
} from "../../api/app/api";
// #ifndef MP-WEIXIN
import { login } from "@/utils/utils.js"
// #endif
export default {
	name: "edge",
	data() {
		return {
			content: "",
			imgList: [],
			permission: "公开",
			location: "所在位置",
			locationInfo: "",
			show: false,
			syncShow: false,
			imgName: [],
			isSync: '否',
			syncList: [{
				name: "是",
				subname: "同步到instagram",
				fontSize: "15",
			},
			{
				name: "否",
				subname: "不同步到instagram",
				fontSize: "15",
			}
			],
			list: [{
				name: "公开",
				subname: "所有人可见",
				fontSize: "15",
			},
			{
				name: "私密",
				subname: "仅自己可见",
				fontSize: "15",
			},
			],
		};
	},
	onLoad() {
		uni.hideTabBar()
	},
	onShow() {
		uni.hideTabBar()
	},
	methods: {
		gobacks() {
			wx.showModal({
				title: '是否离开',
				content: '是否要放弃当前内容离开',
				success: (res) => {
					if (res.confirm) {
						wx.switchTab({
							url: '/pages/home/home'
						})
					}
				}
			});
		},
		goLocation() {
			wx.navigateTo({
				url: "/pages/upload/location",
				events: {
					acceptAddress: (res) => {
						this.location = res.data.title;
						this.locationInfo = res.data;
					},
				},
			});
		},
		look() {
			this.show = true;
		},
		selectClick(res) {
			this.permission = res.name;
			this.show = false;
		},
		selectSyncClick(res) {
			this.isSync = res.name;
			this.syncShow = false;
		},
		choise() {
			uni.chooseMedia({
				count: 9,
				mediaType: ["image", "video"],
				sourceType: ["album", "camera"],
				sizeType: ["original", "compressed"],
				success: (res) => {
					console.log(res);
					if (this.imgList.length + res.tempFiles.length > 9) {
						uni.showToast({
							title: "上传的文件数量和已有的数量超过九张了,请不要超过9张",
						});
					} else {
						res.tempFiles.map((item) => {
							if (!this.imgName.includes(item.tempFilePath)) {
								this.imgList.push(item);
								this.imgName.push(item.tempFilePath);
							}
						});
					}
				},
				fail(err) {
					console.log("错误:", err);
				},
			});
		},
		async release() {
			console.log('开始上传逻辑')
			let isVideo = 0;
			let video_url = "";
			let thumbTempFilePath = "";
			let imgLs = [];
			new Promise((resolve, reject) => {
				if (this.imgList.length === 1 && this.imgList[0].fileType === "video") {
					isVideo = 1;
					let names = this.imgList[0].thumbTempFilePath.split("/");
					names = names[names.length].split(".")[0];
					let ctx = names[names.length].split(".")[1];
					let video_name = this.imgList[0].tempFilePath.split("/");
					video_name = video_name[video_name.length].split(".")[0];
					let video_ctx = video_name[video_name.length].split(".")[1];
					let fn = (cloudPath, filePath, type) =>
						Promise.resolve().then((res) => {
							uni.uploadFile({
								url: 'https://www.roseannepark.love:8000/upload',
								filePath: filePath,
								name: 'file',
								formData: {
									filename: "edge/" + cloudPath
								},
								success: (res) => {
									uni.hideLoading();
									type !== "image" ?
										(video_url = Config.static_url + "edge/" + cloudPath) :
										(thumbTempFilePath = Config.static_url + "edge/" +
											cloudPath);
								}
							})
						});
					uni.showLoading({
						title: "正在上传视频",
					});
					Promise.all([
						fn(names + "." + ctx, this.imgList[0].thumbTempFilePath, "image"),
						fn(video_name + "." + video_ctx, this.imgList[0].tempFilePath),
					]).catch((_) => reject());
				} else {
					let imgArr = this.imgList.map((item, index) => {
						let ls = item.tempFilePath.split("/");
						return Promise.resolve().then((_) => {
							uni.uploadFile({
								url: 'https://www.roseannepark.love:8000/upload',
								filePath: item.tempFilePath,
								name: 'file',
								formData: {
									filename: "edge/" + ls[ls.length - 1],
								},
								success: (res) => {
									imgLs.push(Config.static_url + "edge/" + ls[ls
										.length - 1]);
									if (imgArr.length == imgLs.length) {
										uni.hideLoading();
										resolve();
									}
									if (index === 0) {
										thumbTempFilePath = Config.static_url + "edge/" +
											ls[ls.length - 1];
										console.log('thumbTempFilePath',
											thumbTempFilePath)
									}
								},
								fail: (err) => {
									uni.showToast({
										title: "上传失败",
										icon: 'error',
										duration: 500
									})
								}
							})
						});
					});
					uni.showLoading({
						title: "正在上传图片中",
					});
					Promise.all(imgArr).catch((_) => reject());
				}
			}).then(async (_) => {
				console.log('edgeUser', this.user);
				let count = this.user.edgeCount;
				let infos = {
					user: this.user,
					edge_id: randId(19),
					shortcode: this.user.openid,
					is_video: isVideo,
					display_url: thumbTempFilePath,
					imageList: imgLs,
					video_url: video_url,
					accessibility_caption: "",
					edge_media_to_caption: this.content,
					edge_media_to_comment: 0,
					edge_liked_by: 0,
					taken_at_timestamp: Number(String(+new Date()).slice(0, 10)),
					edge_media_to_tagged_user: "",
					edge_sidecar_to_children: imgLs.join(","),
					video_view_count: 0,
					clips_music_attribution_info: "",
					__typename: isVideo ? "reel" : "edge",
					play_count: 0,
					video_codec: "",
					location: this.locationInfo,
					permission: this.permission,
					origin: 'wx'
				};
				addUserEdge(infos).then(res => {
					wx.showToast({
						title: "上传成功",
						icon: "success",
						duration: 1000,
					});
					this.$store.commit("setUserEdge", infos);
					this.$store.dispatch("changeUserInfo", {
						edgeCount: count + 1,
					});
					uni.switchTab({
						url: '/pages/personal/personal'
					})
				}).catch(err => {
					console.log('err',err)
					wx.showToast({
						title: "上传失败",
						icon: "error",
						duration: 1000,
					});
				})
			});
		},
	},
	computed: {
		user() {
			return this.$store.getters.getUser;
		},
	},
};
</script>

<style lang="scss" scoped>
.line {
	width: 40%;
	height: 6rpx;
	background-color: #4c4c4c;
	position: absolute;
	z-index: 998;
}

.flex-column /deep/ .u-textarea {
	border-color: transparent !important;
	// border-radius: 20rpx;
}

.border {
	border-top: 2rpx solid #dcdcdc;
	// border-bottom: 2rpx solid #dcdcdc;
	padding: 1em 0;
}

.border:last-child {
	border-bottom: 2rpx solid #dcdcdc;
}
</style>